#include "aaudiotester.h"

#include <aaudio/AAudio.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cmath>

// 定义音频流指针
AAudioStream *stream;
// 定义音频数据缓冲区大小，这里假设采样率为44100Hz，单声道，16位采样深度，5秒的音频数据
const int bufferSize = 44100 * 1 * 2 * 5;
// 定义音频数据缓冲区
int16_t audioBuffer[bufferSize];


void runTest() {
    //AAudioResult result;
    aaudio_result_t result;
    AAudioStreamBuilder *builder;

    // 创建音频流构建器
    result = AAudio_createStreamBuilder(&builder);
    if (result!= AAUDIO_OK) {
        printf("Error creating stream builder: %d\n", result);
        return;
    }

    // 设置音频流参数
    AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_I16);
    AAudioStreamBuilder_setChannelCount(builder, 1);
    AAudioStreamBuilder_setSampleRate(builder, 44100);
    AAudioStreamBuilder_setBufferCapacityInFrames(builder, bufferSize / 2);

    // 打开音频流
    result = AAudioStreamBuilder_openStream(builder, &stream);
    if (result!= AAUDIO_OK) {
        printf("Error opening stream: %d\n", result);
        AAudioStreamBuilder_delete(builder);
        return;
    }

    // 释放音频流构建器资源
    AAudioStreamBuilder_delete(builder);

    // 这里简单生成一个正弦波音频数据作为示例
    for (int i = 0; i < bufferSize; i += 2) {
        double t = (double)i / (44100 * 2);
        int16_t sample = (int16_t)(32767 * sin(2 * 3.1415926 * 440 * t));
        audioBuffer[i] = sample;
        audioBuffer[i + 1] = sample;
    }

    // 将音频数据写入音频流
    result = AAudioStream_write(stream, audioBuffer, bufferSize, 1000000);
    if (result!= AAUDIO_OK) {
        printf("Error writing to stream: %d\n", result);
        AAudioStream_close(stream);
        return;
    }

    // 请求开始音频播放
    result = AAudioStream_requestStart(stream);
    if (result!= AAUDIO_OK) {
        printf("Error starting stream: %d\n", result);
        AAudioStream_close(stream);
        return;
    }

    // 等待5秒，让音频播放完成
    sleep(5);

    // 请求停止音频播放
    result = AAudioStream_requestStop(stream);
    if (result!= AAUDIO_OK) {
        printf("Error stopping stream: %d\n", result);
    }

    // 关闭音频流
    AAudioStream_close(stream);

}
